#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/6/16 17:18
# @Author  : huidong.bai
# @File    : conftest.py
# @Software: PyCharm
# @Mail    : MasterBai2018@outlook.com
import os
import pytest
import pickle
import subprocess
import time
import shutil
import signal
import multiprocessing
from Run_Mongo import cmder
from loguru import logger
# mongo日志
logging = logger.opt()
logger.remove()
from src.utils.common import copy_configs, copy_libs, replace_file
from src.utils.file_reader import FileReader
from src.utils.common import async_color_print


@pytest.fixture(scope="session", autouse=True)
def server_programs(request, pytestconfig):
    # 日志写入文件
    log_format = "{time:YYYY-MM-DD HH:mm:ss} | {level}| {name}:{module}:{line:4} | {message}"
    logging.add(sink=open(f'{cmder.suite_dir}/mongo.log', 'w', encoding='UTF-8'), format=log_format, enqueue=True)

    # 解析decoder.conf
    config_reader = FileReader(cmder.config)
    cmder.parse_yaml = config_reader.get_config("ASSERT_PATH_CONFIG")
    cmder.carplay_config = config_reader.get_config("CARPLAY_SDK_CONF")
    cmder.lang_runner = config_reader.get_config("lang")
    cmder.appid = config_reader.get_config("TSA_APPID")

    # suite的lib路径
    cmder.lib_path = os.path.join(cmder.suite_dir, 'lib')
    if not os.path.exists(cmder.lib_path):
        os.makedirs(cmder.lib_path)

    # 创建socket端口文件
    cmder.socket_path = os.path.join(cmder.suite_dir, 'ports')
    if not os.path.exists(cmder.socket_path):
        os.makedirs(cmder.socket_path)

    # 创建log文件
    cmder.log_path = os.path.join(cmder.suite_dir, 'log')
    if not os.path.exists(cmder.log_path):
        os.makedirs(cmder.log_path)

    # 拷贝SpeechEngine服务库和SpeechEngineClient动态库
    cmder.hawk_decoder_so = copy_libs(item="jenkins_aibsLibrary", key="hawk_decoder_so", destination=cmder.lib_path, project=cmder.project)
    cmder.speech_path = copy_libs(item="jenkins_aibsLibrary", key="speechEngine", destination=cmder.lib_path, project=cmder.project)

    # Copy SpeechEngine Configfile
    cmder.speech_config = copy_configs(source_path=cmder.config, dest_dir=cmder.suite_dir, old="MANGO_SUITE_DIR", new=cmder.suite_dir)
    cmder.speech_config = replace_file(cmder.speech_config, "TSAP_MASK_NUM = 63", "TSAP_MASK_NUM = 0")
    cmder.speech_config = replace_file(cmder.speech_config, "#AIBS_MASK_NUM", "AIBS_MASK_NUM")

    os.system(f"chmod +x {cmder.lib_path}/*")
    # 启动VR服务
    start_service(request)


def start_service(request):
    if cmder.gdb == "True":
        async_color_print(("\n======================= 当前处于GDB调试模式 =======================", 'red'))
        async_color_print(("请另起终端, 执行如下指令进行GDB断点调试模式:", 'red'))
        async_color_print((f"SpeechEngine断点:\t\ngdb --args {cmder.speech_path} --config {cmder.speech_config} --lang cmn --log_path {cmder.log_path}", 'red'))
        async_color_print(("==================================================================", 'red'))
        input("按回车键继续...")

    else:
        speech_cmd = [cmder.speech_path, "--config", cmder.speech_config, "--lang", "cmn", "--log_path", cmder.log_path]
        speech_server = start_server(speech_cmd)
        cmder.speech_pid = speech_server

        # 在测试会话结束后停止程序
        def finalizer():
            stop_server(speech_server)

        # 注册停止程序的回调函数
        request.addfinalizer(finalizer)


def start_server(cmd):
    print(cmd)
    process = subprocess.Popen(cmd)
    time.sleep(0.5)
    return process.pid


def stop_server(process):
    os.kill(process, signal.SIGKILL)
